package com.tang;

import com.alibaba.fastjson.JSON;
import com.tang.card.IQiYiCardService;
import com.tang.coupon.CouponResult;
import com.tang.coupon.CouponService;
import com.tang.goods.DeliverReq;
import com.tang.goods.GoodsService;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

@Slf4j
public class PrizeController {

    public AwardRes awardToUser(AwardReq req) {

        AwardRes awardRes = null;

        try {
            log.info("奖品发放开始{}。req:{}", req.getUId(), req);
            // 按照不同类型发放， 1优惠券、2实物商品、3第三方兑换卡（爱奇艺）
            if (Objects.equals(req.getAwardType(), 1)) { // 优惠券
                CouponService couponService = new CouponService();
                CouponResult couponResult = couponService.sendCoupon(req.getUId(), req.getAwardNumber(), req.getBizId());
                if (Objects.equals(AwardRes.SUCCESS, couponResult.getCode())) {
                    awardRes = AwardRes.OK();
                } else {
                    awardRes = AwardRes.ERROR(couponResult.getInfo());
                }

            } else if (Objects.equals(req.getAwardType(), 2)) { // 实物商品
                GoodsService goodsService = new GoodsService();
                DeliverReq deliverReq = new DeliverReq();
                deliverReq.setUserName(queryUserName(req.getUId()));
                deliverReq.setUserPhone(queryUserPhoneNumber(req.getUId()));
                deliverReq.setSku(req.getAwardNumber());
                deliverReq.setOrderId(req.getBizId());
                deliverReq.setConsigneeUserName(req.getExtMap().get("consigneeUserName"));
                deliverReq.setConsigneeUserPhone(req.getExtMap().get("consigneeUserPhone"));
                deliverReq.setConsigneeUserAddress(req.getExtMap().get("consigneeUserAddress"));
                Boolean isSuccess = goodsService.deliverGoods(deliverReq);
                if (isSuccess) {
                    awardRes = AwardRes.OK();
                } else {
                    awardRes = AwardRes.ERROR();
                }

            } else if (Objects.equals(req.getAwardType(), 3)) { // 爱奇艺卡
                String bindMobileNumber = queryUserPhoneNumber(req.getUId());
                IQiYiCardService iQiYiCardService = new IQiYiCardService();
                iQiYiCardService.grantToken(bindMobileNumber, req.getAwardNumber());
                awardRes = AwardRes.OK();

            }
            log.info("奖品发放完成{}。", req.getUId());

        } catch (Exception e) {
            String reqJson = JSON.toJSONString(req);
            log.info("奖品发放失败{}。req:{}", req.getUId(), reqJson);
            awardRes = AwardRes.ERROR(e.getMessage());
        }
        return awardRes;
    }

    private String queryUserName(String uId) {
        return "花花";
    }

    private String queryUserPhoneNumber(String uId) {
        return "15200101232";
    }


}
